<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script lang="ts" setup>
import { ref, computed, unref, toRaw } from 'vue'
import { BasicModal, useModalInner } from '@/components/Modal'
import { BasicForm, useForm } from '@/components/Form'
import { classifyTypeFormSchema } from './classify.data'
import { updateDeviceType, addDeviceType } from '@/api/collection/device'
import { addOrUpdateClassify, deleteClassify } from '@/api/collection/classify'

const emit = defineEmits(['success', 'register'])

const isUpdate = ref(true)
const rowId = ref('')
const addChildren = ref(false)

const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
  labelWidth: 100,
  baseColProps: { span: 24 },
  schemas: classifyTypeFormSchema,
  showActionButtonGroup: false,
  actionColOptions: {
    span: 23,
  },
})

const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  resetFields()
  setModalProps({ confirmLoading: false })
  isUpdate.value = !!data?.isUpdate
  addChildren.value = !!data?.addChildren
  if (unref(addChildren)) {
    rowId.value = data.ret
  }
  if (unref(isUpdate)) {
    rowId.value = data.ret
    // console.log(data.ret);

    setFieldsValue({
      ...data.ret,
      classifyNameCopy: data.ret.classifyName
    })
  }
})

const getTitle = computed(() => (!unref(isUpdate) ? '新增数据类型' : '编辑数据类型'))

async function handleSubmit() {
  try {
    const values = await validate()
    setModalProps({ confirmLoading: true })
    if (unref(isUpdate)) {
      const rawObj = toRaw(rowId.value)
      const params = { ...values, classifyName: values.classifyNameCopy }
      const obj = Object.assign({}, rawObj, params)
      await addOrUpdateClassify(obj)
    }
    else {
      let params;
      if (unref(addChildren)) {
        params = {
          ...values,
          classifyName: values.classifyNameCopy,
          rootClassifyId: rowId.value.rootClassifyId,
          parentClassifyId: rowId.value.classifyId
        }
        // console.log(rowId.value, params);
      } else params = { ...values, classifyName: values.classifyNameCopy, rootClassifyId: null }
      await addOrUpdateClassify(params)
    }
    closeModal()
    emit('success')
  } finally {
    setModalProps({ confirmLoading: false })
  }
}

</script>
